<template>
	<view class="counter">
		<view class="reduce btn" @click="reduce" :class="{ disable: val <= 0 }">-</view>
		<view class="count">{{ val }}</view>
		<view class="add btn" @click="add" :class="{ disable: max && val >= max }">+</view>
	</view>
</template>

<script>
	export default {
		name: 'c-counter',
		props: {
			value: {
				type: Number,
				default: 1
			},
			max: {
				type: Number
			},
		},
		data() {
			return {
				oldValue: 0
			}
		},
		computed: {
			val: {
				get() {
					return this.value
				},
				set(val) {
					this.$emit('input', val);
					this.$emit('change', val);
				}
			}
		},
		methods: {
			reduce() {
				if (this.value <= 0) return
				this.oldValue = this.value
				this.val -= 1
			},
			add() {
				if (this.max && this.value >= this.max) return
				this.oldValue = this.value
				this.val += 1
			}
		}
	};
</script>

<style lang="less" scoped>
	.counter {
		display: flex;
		align-items: center;

		.disable {
			color: #BBBBBB;
			border: 2rpx solid #BBBBBB !important;
		}

		.count {
			width: 58rpx;
			height: 48rpx;
			background: #F5F5F5;
			border-radius: 8rpx;
			display: flex;
			justify-content: center;
			align-items: center;
			font-size: 26rpx;
			font-weight: 500;
			margin: 0 15rpx;
		}

		.reduce {
			margin-top: -2rpx;
		}

		.add {
			position: relative;
			margin-top: -2rpx;
		}

		.btn {
			width: 46rpx;
			height: 32rpx;
			border-radius: 16rpx;
			border: 1rpx solid #333333;
			display: flex;
			justify-content: center;
			align-items: center;
		}
	}
</style>